package controllers

import (
	"chat/app/repositories"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/plugins/cors"
)

type NestPreparer interface {
	NestPrepare()
}

type baseController struct {
	beego.Controller
	repositories.MemberRepository
}

func (this *baseController) Prepare() {
	this.Data["pageStartTime"] = time.Now()
	this.Layout = "layout/container.html"

	//获取随机聊天名
	this.Data["chatInfo"] = this.MemberRepository.GetName(&this.Controller)

	// todo 添加跨域信息
	//InsertFilter是提供一个过滤函数

	// log.Println("REQUEST:", this.Ctx.Request.Header.Get("Origin"), "-------------------")
	origin := this.Ctx.Request.Header.Get("Origin")
	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		//允许访问所有源
		// AllowAllOrigins: true,
		AllowOrigins: []string{origin},
		//可选参数"GET", "POST", "PUT", "DELETE", "OPTIONS" (*为所有)
		//其中Options跨域复杂请求预检
		AllowMethods: []string{"*"},
		//指的是允许的Header的种类
		AllowHeaders: []string{"*"},
		//公开的HTTP标头列表
		ExposeHeaders: []string{"Content-Length"},
		//如果设置，则允许共享身份验证凭据，例如cookie
		AllowCredentials: true,
	}))
	////断言判断,是否实现了  NestPreparer 接口
	if app, ok := this.AppController.(NestPreparer); ok {
		app.NestPrepare()
	}
}
